if-else


The if...else statement is used to execute a block of code based on a specified condition. If the condition is true, the block of code inside the if statement is executed. Otherwise, the block of code inside the else statement is executed.

1. Basic if...else Statement

Here is an example of a basic if...else statement:

let isRaining = true;

if (isRaining) {
    console.log("Take an umbrella!");
} else {
    console.log("No need for an umbrella.");
}

2. else if Statement

The else if statement is used to specify multiple conditions:

let temperature = 30;

if (temperature > 30) {
    console.log("It's hot outside!");
} else if (temperature < 15) {
    console.log("It's cold outside!");
} else {
    console.log("The weather is moderate.");
}

3. Nested if...else Statement

You can also nest if...else statements within each other:

let age = 20;
let hasPermission = true;

if (age >= 18) {
    if (hasPermission) {
        console.log("You can enter the club.");
    } else {
        console.log("You need permission to enter the club.");
    }
} else {
    console.log("You are too young to enter the club.");
}

4. Ternary Operator

The ternary operator is a shorthand for the if...else statement:


let isMember = true;
let discount = isMember ? 10 : 0;
console.log(`You get a ${discount}% discount.`); // Outputs: You get a 10% discount.